﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UIShare;
using EFong.View.Proxy;
using EFong.View.Customer;

namespace EFong.View.OtherBusiness
{
    public partial class Frm_OtherBusinessEdit : BasicForm
    {
        private Proxy.MasterServiceProxy _masterProxy {get{ return Proxy.MasterServiceProxy.GetInstance();}}
        private Proxy.BusinessServiceProxy _businessProxy {get{ return Proxy.BusinessServiceProxy.GetInstance();}}
        private Proxy.BaseServiceProxy _baseProxy {get{ return Proxy.BaseServiceProxy.GetInstance();}}

        public Contract.ROtherBusiness ReturnValue = null;

        public Frm_OtherBusinessEdit()
        {
            InitializeComponent();
            spe_VendorDiscountOrBasePrice.SetValue(null);
            spe_PrintTotalPrice.SetValue(null);

            //cmb_BankAccount.ReadOnly(true);
        }

        protected override void InitFields()
        {
        }

        protected override void Events()
        {
            this.btn_CustomerData.Click += (s, e) =>
                {
                    editCustomer();
                };
            this.cmb_Project.SelectedIndexChanged += (s, e) =>
                {
                    Contract.Project project = this.cmb_Project.GetValue<Contract.Project>();

                    if (project == null)
                    {
                        this.cmb_SubProject.Properties.BindingData(null);
                        bds_Vendor.BindingData(null);
                    }
                    else
                    {
                        this.cmb_SubProject.Properties.BindingData(project.SubProjectList);
                        bds_Vendor.BindingData(_masterProxy.GetVendorByProject(project).ReturnValue);
                    }

                    this.cmb_SubProject.SetValue(default(Contract.SubProject));
                    this.cmb_Vendor.SetValue(default(Contract.RVendor));
                };
            this.cmb_Customer.EditValueChanged += (s, e) =>
                {
                    Contract.RCustomer customer = this.cmb_Customer.GetValue() as Contract.RCustomer;

                    if (customer != null)
                    {
                        SelCust = _masterProxy.GetCustomerByID(customer.ID).ReturnValue;
                        this.txtAddress.SetText(SelCust.Address);
                    }
                    else
                    {
                        SelCust = null;
                    }
                };

            this.cmb_Vendor.EditValueChanged += (s, e) =>
            {
                Contract.RVendor vendor = this.cmb_Vendor.GetValue() as Contract.RVendor;

                if (vendor != null)
                {
                    SelVendor = _masterProxy.GetVendorByID(vendor.ID).ReturnValue;
                }
                else
                {
                    SelVendor = null;
                }
            };


            this.spe_Price.ValueChanged += (s, e) => { updateTotalFields(); };
            this.spe_Qty.ValueChanged += (s, e) => { updateTotalFields(); };
            this.spe_VendorDiscountOrBasePrice.ValueChanged += (s, e) => { updateTotalFields(); };
            this.rad_BasePrice.CheckedChanged += (s, e) => { updateTotalFields(); };
            this.rad_VendorDiscount.CheckedChanged += (s, e) => { updateTotalFields(); };

            //this.cmb_PaymentType.SelectedIndexChanged += (s, e) =>
            //{
            //    this.cmb_BankAccount.SetValue(default(Contract.BankAccount));
            //    this.cmb_BankAccount.ReadOnly(this.cmb_PaymentType.SelectedIndex <= 0);
            //};
        }

        protected override void LoadDatas()
        {
            bds_Customer.BindingData(_masterProxy.GetAllCustomer().ReturnValue);
            this.cmb_Project.Properties.BindingData(_masterProxy.GetAllProject().ReturnValue);
            this.cmb_OrderUser.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);

            //this.cmb_BankAccount.Properties.BindingData(_masterProxy.GetAllEffectivedBankAccount());

            if (this.cmb_OrderUser.GetValue() == null)
                this.cmb_OrderUser.SetValue(AppParameters.LoginUser);

            this.cmb_ProvideTicketUser.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);
            this.cmb_SalesMan.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);
        }

        private void bar_Main_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "bbt_Save":
                    this.save();
                    break;
                case "bbt_Close":
                    this.Close();
                    break;
                default:
                    break;
            }
        }

        private string returnRef;

        private void save()
        {
            Contract.OtherBusiness otherBusiness = null;

            UIOperManager.SaveData(
                () =>
                {
                    if (this.cmb_Customer.GetValue() == null)
                    {
                        MsgBox.Info("请选择客户.");
                        return false;
                    }

                    if (this.cmb_Project.GetValue() == null)
                    {
                        MsgBox.Info("请选择项目.");
                        return false;
                    }

                    if (!this.dte_ProjectDate.GetValue().HasValue)
                    {
                        MsgBox.Info("请选择项目日期.");
                        return false;
                    }

                    if (this.cmb_Vendor.GetValue() == null)
                    {
                        MsgBox.Info("请选择供应商.");
                        return false;
                    }

                    return true;
                },
                () =>
                {
                    otherBusiness = getOrder();
                    updateToOrder(otherBusiness);
                    var result = _businessProxy.UpdateOtherBusiness(Order);
                    if (result.IsSuccess)
                    {
                        returnRef = result.ReturnValue;
                        this.txt_OrderRef.Text = returnRef;
                    }

                    return result.IsSuccess; 
                },
                string.Empty,
                () =>
                {
                    DialogResult = DialogResult.OK;
                    MsgBox.Info(string.Format("{0} 保存成功", returnRef));
                    this.Close();

                    ReturnValue = new Contract.ROtherBusiness()
                    {
                        ID = Order.ID,
                        Customer = Order.Customer.Name,
                        CustomerStatus = Order.CustomerStatus,
                        Intergral = 0,
                        OrderDate = Order.OrderDate,
                        OrderUserText = Order.OrderUser.Name,
                        Ref = returnRef,
                        Remark = Order.Remark,
                        Status = Order.Status,
                        TotalPrice = Order.TotalPrice,
                        VendorStatus = Order.VendorStatus
                    };
                });
        }

        private void editCustomer()
        {
            if (SelCust == null)
                return;

            Frm_CustomerEdit frm = new Frm_CustomerEdit();
            frm.Text = "客户详细资料";
            if (!AppParameters.AllowEditCustomer)
                frm.ViewState = ViewStates.BROWSER;
            frm.Load += (s, e) =>
                {
                    frm.CurCust = SelCust;
                };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
                SelCust = frm.CurCust;
        }

        private void updateTotalFields()
        {
            Contract.OtherBusiness otherBusiness = getOrder();
            this.spe_TotalPrice.SetValue(otherBusiness.TotalPrice);
            this.spe_TotalProfit.SetValue(otherBusiness.TotalProfit);
            this.spe_TotalVendorPrice.SetValue(otherBusiness.TotalVendorPrice);
        }

        #region Order
        // current other business
        private Contract.OtherBusiness _order;
        public Contract.OtherBusiness Order
        {
            get { return _order; }
            set
            {
                _order = value;
                onOrderChanged();
            }
        }

        private void onOrderChanged()
        {
            if (Order == null)
            {
                // clear other business datas
            }
            else
            {
                //set other business datas
                if (Order.OrderUser != null)
                    this.cmb_OrderUser.SetValue(Order.OrderUser);
                if (Order.OrderDate != null)
                    this.dte_OrderDate.SetValue(Order.OrderDate);
                this.cmb_Customer.SetValue(Order.Customer);
                SelCust = Order.Customer;
                this.cmb_Project.SetValue(Order.Project);
                this.cmb_SubProject.SetValue(Order.SubProject);
                this.txt_ProjectContent.SetText(Order.ProjectText);
                if (Order.Vendor != null)
                {
                    Contract.Vendor vendor = new Contract.Vendor();
                    vendor.ID = Order.Vendor.ID;
                    vendor.Name = Order.Vendor.Name;
                    this.cmb_Vendor.SetValue(vendor);
                }
                SelVendor = Order.Vendor;
                this.txt_CustomerName.SetText(Order.CustomerName);
                this.dte_ProjectDate.SetValue(Order.ProjectDate);
                this.spe_Price.SetValue(Order.Price);
                this.spe_Qty.SetValue(Order.Qty);
                this.txt_ProjectContent.SetText(Order.Content);
                this.cmb_SalesMan.SetValue(Order.Salesman);
                this.cmb_ProvideTicketUser.SetValue(Order.ProvideTicketUser);
                this.dte_DeliveryDate.SetValue(Order.DeliveryDate);

                this.txt_CPerson.SetText(Order.ContactPerson);
                this.txt_CPersonTel.SetText(Order.联系电话);
                this.txt_CPersonPhone.SetText(Order.移动电话);

                if (Order.VendorDiscount.HasValue)
                {
                    this.rad_VendorDiscount.Checked = true;
                    this.spe_VendorDiscountOrBasePrice.SetValue(Order.VendorDiscount);
                }
                else if (Order.BasePrice.HasValue)
                {
                    this.rad_BasePrice.Checked = true;
                    this.spe_VendorDiscountOrBasePrice.SetValue(Order.BasePrice);
                }
                else
                {
                    this.rad_BasePrice.Checked = true;
                    this.rad_VendorDiscount.Checked = false;
                    this.spe_VendorDiscountOrBasePrice.SetValue(null);
                }

                //this.cmb_PaymentType.SetDisplay(Order.PaymentType);
                //if (Order.BankAccount != null)
                //    this.cmb_BankAccount.SetValue(Order.BankAccount);

                this.txt_Remark.SetText(Order.Remark);
                this.spe_PrintTotalPrice.SetValue(Order.PrintTotalPrice);
                this.spe_Intergral.SetValue(Order.Intergral);
                this.cmb_CreditTerm.SetValue(Order.CreditTerm);
                this.txtAddress.SetText(Order.Address);
            }
        }

        private Contract.OtherBusiness getOrder()
        {
            Contract.OtherBusiness order = new Contract.OtherBusiness();

            order.Content = this.txt_ProjectContent.GetText();
            order.Customer = SelCust;
            order.Intergral = this.spe_Intergral.GetValue();
            order.OrderDate = this.dte_OrderDate.GetValue();
            order.OrderUser = this.cmb_OrderUser.GetValue() as Contract.User;
            order.Price = this.spe_Price.GetValue();
            order.PrintTotalPrice = this.spe_PrintTotalPrice.GetValue(true);
            order.Project = this.cmb_Project.GetValue() as Contract.Project;
            order.Qty = (int)this.spe_Qty.GetValue();
            order.Remark = this.txt_Remark.GetText();
            order.SubProject = this.cmb_SubProject.GetValue() as Contract.SubProject;
            order.Vendor = SelVendor;
            order.CustomerName = this.txt_CustomerName.GetText();
            order.Currency = _baseProxy.GetCNYCurrency().ReturnValue;
            order.ProjectDate = this.dte_ProjectDate.GetValue().Value;
            order.CreditTerm = this.cmb_CreditTerm.GetValue() as String;
            order.DeliveryDate = this.dte_DeliveryDate.GetValue();

            order.ContactPerson = this.txt_CPerson.GetText();
            order.联系电话 = this.txt_CPersonTel.GetText();
            order.移动电话 = this.txt_CPersonPhone.GetText();

            string creditTermValue = this.cmb_CreditTerm.GetValue() as String;
            if (string.IsNullOrEmpty(creditTermValue))
                order.CreditTerm = string.Empty;
            else
                order.CreditTerm = creditTermValue;

            decimal? vendorDiscountOrBasePrice = this.spe_VendorDiscountOrBasePrice.GetValue();
            if (vendorDiscountOrBasePrice.HasValue && rad_VendorDiscount.Checked)
            {
                order.VendorDiscount = vendorDiscountOrBasePrice;
                order.BasePrice = null;
            }
            else if (vendorDiscountOrBasePrice.HasValue && rad_BasePrice.Checked)
            {
                order.BasePrice = vendorDiscountOrBasePrice;
                order.VendorDiscount = null;
            }
            else
            {
                order.BasePrice = order.VendorDiscount = null;
            }

            order.Salesman = this.cmb_SalesMan.GetValue() as Contract.User;
            order.ProvideTicketUser = this.cmb_ProvideTicketUser.GetValue() as Contract.User;
            order.Address = this.txtAddress.GetText();
            //order.BankAccount = this.cmb_BankAccount.GetValue() as Contract.BankAccount;
            //order.PaymentType = this.cmb_PaymentType.GetDisplay();

            return order;
        }

        private void updateToOrder(Contract.OtherBusiness order)
        {
            Order.BasePrice = order.BasePrice;
            Order.Content = order.Content;
            Order.CreditTerm = order.CreditTerm;
            Order.Currency = order.Currency;
            Order.Customer = order.Customer;
            Order.CustomerName = order.CustomerName;
            Order.Intergral = order.Intergral;
            Order.OrderDate = order.OrderDate;
            Order.OrderUser = order.OrderUser;
            Order.Price = order.Price;
            Order.PrintTotalPrice = order.PrintTotalPrice;
            Order.Project = order.Project;
            Order.ProjectDate = order.ProjectDate;
            Order.Qty = order.Qty;
            Order.Remark = order.Remark;
            Order.Salesman = order.Salesman;
            Order.DeliveryDate = order.DeliveryDate;

            Order.ContactPerson = order.ContactPerson;
            Order.联系电话 = order.联系电话;
            Order.移动电话 = order.移动电话;

            Order.SubProject = order.SubProject;
            Order.Vendor = order.Vendor;
            Order.VendorDiscount = order.VendorDiscount;
            Order.CreditTerm = order.CreditTerm;
            Order.ProvideTicketUser = order.ProvideTicketUser;
            Order.PaymentType = order.PaymentType;
            Order.BankAccount = order.BankAccount;
            Order.Address = order.Address;
        }
        #endregion

        #region Customer
        private Contract.Customer _selCust;
        public Contract.Customer SelCust
        {
            get { return _selCust; }
            set
            {
                _selCust = value;
                onSelCustChanged();
            }
        }

        private void onSelCustChanged()
        {
            if (SelCust == null)
            {
                this.cmb_SalesMan.SetValue(default(Contract.User));
                this.txt_CPerson.SetText(null);
                this.txt_CPersonTel.SetText(null);
                this.txt_CPersonPhone.SetText(null);
            }
            else
            {
                this.cmb_SalesMan.SetValue(SelCust.Salesman);
                this.txt_CPerson.SetText(SelCust.ContactPerson1);
                this.txt_CPersonTel.SetText(SelCust.ContactPerson1Tel);
                this.txt_CPersonPhone.SetText(SelCust.ContactPerson1Phone1);
            }
        }
        #endregion

        #region  Vendor

        private Contract.Vendor _selVendor;
        public Contract.Vendor SelVendor
        {
            get { return _selVendor; }
            set
            {
                _selVendor = value;
            }
        }

        #endregion


        protected override void OnViewStateChanged()
        {
            switch (ViewState)
            {
                case ViewStates.EDIT:
                    if (!AppParameters.IsAdRole)
                    {
                        //cmb_PaymentType.ReadOnly(true);
                        //cmb_BankAccount.ReadOnly(true);
                        cmb_CreditTerm.ReadOnly(true);
                        spe_Price.ReadOnly(true);
                        spe_Qty.ReadOnly(true);
                        rad_VendorDiscount.ReadOnly(true);
                        rad_BasePrice.ReadOnly(true);
                        spe_VendorDiscountOrBasePrice.ReadOnly(true);
                        cmb_Vendor.ReadOnly(true);
                        cmb_Customer.ReadOnly(true);
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
